// 粉笔网公用请求方法 - 简化版
const https = require('https');
const config = require('../config');

/**
 * 粉笔网API请求类 - 简化版本
 */
class FenbiRequest {
  constructor() {
    this.baseHeaders = {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
      'Accept': 'application/json, text/plain, */*',
      'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
      'Origin': 'https://spa.fenbi.com',
      'Referer': 'https://spa.fenbi.com/',
      'Sec-Ch-Ua': '"Not;A=Brand";v="99", "Google Chrome";v="139", "Chromium";v="139"',
      'Sec-Ch-Ua-Mobile': '?0',
      'Sec-Ch-Ua-Platform': '"macOS"',
      'Sec-Fetch-Dest': 'empty',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Site': 'same-site',
      'Cache-Control': 'no-cache',
      'Pragma': 'no-cache'
    };

    // 添加认证cookie
    if (config.getCookieHeader()) {
      this.baseHeaders['Cookie'] = config.getCookieHeader();
    }
  }

  /**
   * 通用请求方法 - 简化版
   * @param {string} url - 请求URL
   * @param {Object} options - 请求选项
   * @returns {Promise} 返回响应数据
   */
  async request(url, options = {}) {
    const method = options.method || 'GET';

    const requestOptions = {
      method: method,
      headers: {
        ...this.baseHeaders,
        ...options.headers
      }
    };

    // 如果有请求体，添加Content-Type
    if (options.body) {
      if (typeof options.body === 'object') {
        if (options.contentType === 'json') {
          requestOptions.headers['Content-Type'] = 'application/json';
          requestOptions.body = JSON.stringify(options.body);
        } else {
          // 默认使用表单格式
          requestOptions.headers['Content-Type'] = 'application/x-www-form-urlencoded';
          requestOptions.body = this.objectToFormData(options.body);
        }
      } else {
        requestOptions.body = options.body;
      }
    }

    try {
      console.log(`请求: ${method} ${url}`);

      const response = await this.makeRequest(url, requestOptions);

      // 检查响应状态
      if (response.status >= 200 && response.status < 300) {
        const data = await this.parseResponse(response);
        console.log(`请求成功: ${response.status}`);
        return {
          success: true,
          status: response.status,
          headers: response.headers,
          data: data
        };
      } else {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

    } catch (error) {
      console.error(`请求失败:`, error.message);
      return {
        success: false,
        error: error.message,
        status: error.status || 0
      };
    }
  }

  /**
   * 执行HTTP请求 - 简化版
   */
  async makeRequest(url, options) {
    return new Promise((resolve, reject) => {
      const req = https.request(url, options, (res) => {
        let data = '';

        res.on('data', (chunk) => {
          data += chunk;
        });

        res.on('end', () => {
          resolve({
            status: res.statusCode,
            statusText: res.statusMessage,
            headers: res.headers,
            body: data
          });
        });
      });

      req.on('error', (error) => {
        reject(error);
      });

      if (options.body) {
        req.write(options.body);
      }

      req.end();
    });
  }

  /**
   * 解析响应数据
   */
  async parseResponse(response) {
    const contentType = response.headers['content-type'] || '';

    if (contentType.includes('application/json')) {
      try {
        return JSON.parse(response.body);
      } catch (error) {
        console.warn('JSON解析失败，返回原始数据');
        return response.body;
      }
    }

    return response.body;
  }

  /**
   * 对象转表单数据
   */
  objectToFormData(obj) {
    return Object.keys(obj)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
      .join('&');
  }

  /**
   * GET请求快捷方法
   */
  async get(url, options = {}) {
    return this.request(url, { method: 'GET', ...options });
  }

  /**
   * POST请求快捷方法
   */
  async post(url, body, options = {}) {
    return this.request(url, {
      method: 'POST',
      body,
      ...options
    });
  }

  /**
   * PUT请求快捷方法
   */
  async put(url, body, options = {}) {
    return this.request(url, {
      method: 'PUT',
      body,
      ...options
    });
  }

  /**
   * DELETE请求快捷方法
   */
  async delete(url, options = {}) {
    return this.request(url, { method: 'DELETE', ...options });
  }
}

// 创建单例实例
const fenbiRequest = new FenbiRequest();

module.exports = fenbiRequest;
